<template>
  <div class="org">
    <div
      style="margin-bottom: 10px; display: flex; justify-content: space-between"
    >
      <div style="float: left">
        <el-button
          v-permission="'company_organizational_branch_create'"
          type="primary"
          plain
          @click="handleClickAdd"
          data-tracker="P37-1"
        >
          <i class="el-icon-plus"></i>
          新增组织
        </el-button>
        <el-button
          v-permission="'company_organizational_branch_delete'"
          type="danger"
          plain
          @click="handleClickDelete"
          data-tracker="P37-2"
        >
          <i class="el-icon-delete"></i>
          删除组织
        </el-button>
      </div>
      <div style="float: right">
        <el-pagination
          background
          small
          :current-page="oPaginations.pageIndex"
          :page-sizes="oPaginations.pageSizes"
          :page-size="oPaginations.pageSize"
          :layout="oPaginations.layout"
          :total="oPaginations.total"
          @size-change="handleOrgSizeChange"
          @current-change="handleOrgCurrentChange"
        />
      </div>
    </div>
    <el-table
      border
      stripe
      :data="orgList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="name" label="组织名称" width="160" />
      <el-table-column prop="abbre_name" label="组织简称" width="150" />
      <el-table-column prop="branch_type" label="组织类型" width="150">
        <template slot-scope="scope">
          {{ scope.row.branch_type | filterType }}
        </template>
      </el-table-column>
      <el-table-column prop="code" label="组织代码" width="220" />
      <el-table-column prop="property" label="组织来源" width="150">
        <template slot-scope="scope">
          {{ scope.row.property | filterProperty }}
        </template>
      </el-table-column>
      <el-table-column prop="parent_branch" label="上级组织" width="220" />
      <el-table-column prop="head" label="负责人" width="150" />
      <el-table-column prop="head_mobile" label="负责人手机号" width="150" />
      <el-table-column prop="head_id_card" label="身份证" width="240" />
      <el-table-column prop="business_phone" label="业务电话" width="150" />
      <el-table-column prop="address" label="地址" width="280" />
      <el-table-column prop="status" label="启用状态" width="100">
        <template slot-scope="scope">
          {{ scope.row.status | filterStatus }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="320" />
      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-permission="'company_organizational_branch_detail'"
            size="small"
            type="text"
            data-tracker="P37-3"
            @click="handleClick(scope.row, 'detail')"
            >查看
          </el-button>
          <el-button
            v-permission="'company_organizational_branch_update'"
            size="small"
            type="text"
            data-tracker="P37-4"
            @click="handleClick(scope.row, 'edit')"
            >编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加表格 -->
    <el-dialog
      ref="perForm"
      :close-on-click-modal="false"
      :title="`${showText}`"
      :visible="showOrgDialog"
      @close="handleCloseDialog"
    >
      <!-- 表单 -->
      <el-form
        ref="orgform"
        label-width="120px"
        :model="formData"
        :rules="rules"
        :inline="true"
        :disabled="mode === 'detail'"
        class="ruleForm"
      >
        <el-form-item label="组织名称" prop="name">
          <el-input v-model="formData.name" style="width: 100%" />
        </el-form-item>
        <el-form-item label="组织简称" prop="abbre_name">
          <el-input v-model="formData.abbre_name" style="width: 100%" />
        </el-form-item>
        <el-form-item label="组织代码" prop="code">
          <el-input v-model="formData.code" style="width: 100%" />
        </el-form-item>
        <el-form-item label="组织类型" prop="branch_type">
          <!-- <el-input v-model="formData.branch_type" style="width:100%" /> -->
          <el-select
            v-model="formData.branch_type"
            placeholder="请选择组织类型"
            @change="handleChangebranchType"
          >
            <el-option
              v-for="(item, index) in types"
              :key="index"
              :label="item.value"
              :value="item.id + ''"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="组织属性" prop="property">
          <el-select v-model="formData.property" placeholder="请选择组织属性">
            <el-option
              v-for="(item, index) in propertys"
              :key="index"
              :label="item.value"
              :value="item.id"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="上级组织" prop="description">
          <el-input v-model="formData.pid" style="width:100%" />
        </el-form-item> -->
        <el-form-item label="负责人" prop="head">
          <el-input v-model="formData.head" style="width: 100%" />
        </el-form-item>
        <el-form-item label="手机" prop="head_mobile">
          <el-input v-model="formData.head_mobile" style="width: 100%" />
        </el-form-item>
        <el-form-item label="身份证" prop="head_id_card">
          <el-input v-model="formData.head_id_card" style="width: 100%" />
        </el-form-item>
        <el-form-item label="业务电话" prop="business_phone">
          <el-input v-model="formData.business_phone" style="width: 100%" />
        </el-form-item>
        <el-form-item label="地址" prop="area">
          <!-- :props="{ expandTrigger: 'hover' }" -->
          <el-cascader
            v-model="formData.area"
            placeholder="请选择地区"
            :options="areaData"
            :props="{
              value: 'id',
              label: 'name',
              children: 'next_level_data',
            }"
            @change="handleAddrChange"
            ref="cascaderAddr"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="formData.address" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option
              v-for="(item, index) in status"
              :key="index"
              :label="item.value"
              :value="item.id"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" style="width: 100%" />
        </el-form-item>
        <el-form-item
          label="分管城市"
          v-if="branchTypeShow"
          class="cityOverflow"
        >
          <el-cascader
            :props="propsBranchType"
            :options="areaData24"
            style="width: 308px"
            v-model="formData.region"
            placeholder="请选择省市"
            :key="Math.random()"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <!-- 操作按钮 -->
      <el-row type="flex" justify="center">
        <el-col :span="8">
          <el-button
            :data-tracker="mode === 'add' ? 'P37-10' : 'P37-14'"
            @click="handleCloseDialog"
            >取消</el-button
          >
          <el-button
            type="primary"
            :data-tracker="mode === 'add' ? 'P37-9' : 'P37-13'"
            @click="handleClickOk"
            >确定</el-button
          >
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import {
  organizationBox,
  organizationList,
  newlyorganization,
  amendNewlyorgan,
  queryorganization,
  bolckorganization,
  removeOrganization,
  organizationDetail,
  getRegionList,
  BranchRegionlist,
} from "@/api/organization";
import { Types, Propertys, Status } from "../constant";
import { regionList } from "../../material/common/common";
import { reqDictionaryOptions } from "@/api/earlywarning";
import { time } from "echarts";
export default {
  name: "organization",
  data() {
    return {
      activeName: "zzmessage",
      openeds: ["1"],
      tableData: [
        {
          name: "11",
          AbbreName: "222",
          BranchType: "333",
          Code: "444",
          Property: "5555",
          Pid: "6666",
          Head: "7777",
          HeadMobile: "8888",
          HeadIdCard: "8899999",
          BusinessPhone: "99990000",
          address: "aaaaa",
          Status: "bbbbbb",
          Remark: "ccccc",
        },
      ],
      tableData1: [
        {
          username: "员工1",
          sex: "男",
          moblie: "13810777777",
          zhanghao: "dushi@123.com",
          Headcard: "1112121221212",
          AbbreID: "221212122",
          position: "部门",
          desc: "21321333",
          istype: "启用",
          juese: "业务员工",
        },
      ],
      currentPage: 5,
      organizations: [],
      orgList: [],
      showOrgDialog: false,
      formData: {
        // name: "安德转运中心",
        // abbre_name: "AD",
        // code: "02345",
        // branch_type: "0",
        // property: "0",
        // head: "李欣欣",
        // head_mobile: "15677778888",
        // head_id_card: "130633199878997687",
        // business_phone: "15677778888",
        // province_id: 120000,
        // city_id: 120200,
        // district_id: 120221,
        // address: "嗷嗷",
        // status: "1",
        // pid: "15",
        region: [],
      },
      areaData: [],
      areaData2: [],
      areaData24: [],
      deleteParams: [],
      // 部门分页
      oPaginations: {
        pageIndex: 1, // 当前位于哪页
        pageSize: 5, // 1页显示多少条
        pageSizes: [5, 10, 15, 20], //每页显示多少条
        total: 200,
        layout: "total, sizes, prev, pager, next, jumper", // 翻页属性
      },
      rules: {
        name: [{ required: true, message: "请输入组织名称", trigger: "blur" }],
        // abbre_name: [
        //   { required: true, message: "请输入组织简称", trigger: "blur" },
        // ],

        // code: [{ required: true, message: "请输入组织代码", trigger: "blur" }],
        branch_type: [
          { required: true, message: "请选择组织类型", trigger: "blur" },
        ],
        property: [
          { required: true, message: "请选择组织属性", trigger: "blur" },
        ],
        // head: [{ required: true, message: "请填写负责人", trigger: "blur" }],
        // head_mobile: [
        //   { required: true, message: "请输入负责人手机号", trigger: "blur" },
        // ],
        head_id_card: [
          { required: false, message: "请输入活动名称", trigger: "blur" },
        ],
        business_phone: [
          { required: false, message: "请输入活动名称", trigger: "blur" },
        ],
        // address: [
        //   { required: true, message: "请输入详细地址", trigger: "blur" },
        // ],
        // area: [{ required: true, message: "请选择地址", trigger: "blur" }],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
        region: [
          { required: true, message: "请选择网点城市", trigger: "blur" },
        ],
      },
      mode: "",
      OpitonsData: [],
      branchTypeShow: false,
      branchTypeShowVal: "",
      propsBranchType: {
        multiple: true,
        emitPath: true,
        value: "id",
        label: "name",
        children: "next_level_data",
      },
    };
  },
  props: ["currentOrgInfo"],
  computed: {
    showText() {
      const { mode } = this;
      if (mode === "add") {
        return "新增组织";
      } else if (mode === "edit") {
        return "编辑组织";
      } else if (mode === "detail") {
        return "组织详情";
      }
    },
  },
  filters: {
    filterType(type) {
      const obj = Types.find((item) => item.id === String(type)) || {};
      return obj.value;
    },
    filterProperty(p) {
      const obj = Propertys.find((item) => item.id === String(p)) || {};
      return obj.value;
    },
    filterStatus(s) {
      const obj = Status.find((item) => item.id === String(s)) || {};
      return obj.value;
    },
  },
  watch: {
    currentOrgInfo: function (newV) {
      this.getOrganizationList();
    },
  },
  created() {
    // this.areaData = AreaJson;
    // this.types = [
    //   { id: "0", value: "揽收网点" },
    //   { id: "1", value: "干线网点" },
    //   { id: "3", value: "大区" },
    //   { id: "2", value: "其他" },
    // ];
    this.types = Types;
    this.propertys = Propertys;
    this.status = [
      { id: "0", value: "启用" },
      { id: "1", value: "禁用" },
    ];
  },
  mounted() {
    this.provincectiy();
  },
  methods: {
    handleChangebranchType(val) {
      if (val === "2") {
        this.branchTypeShow = false;
      } else {
        this.branchTypeShow = true;
      }
    },
    // 地址库
    provincectiy() {
      var city = regionList(0).then((res) => {
        this.areaData = res.data;
        const data = JSON.parse(JSON.stringify(res.data));

        data.forEach((item) => {
          item.next_level_data.forEach((iten) => {
            iten.next_level_data = undefined;
          });
        });
        this.areaData2 = data;
      });
    },
    //  新增组织
    handleClickAdd() {
      this.formData = {};
      this.mode = "add";
      this.showOrgDialog = true;
      this.PageBranchRegionlist(this.areaData2);
    },
    // 删除组织
    handleClickDelete() {
      if (this.deleteParams.length === 0) {
        this.$message({
          message: "选中后可继续进行操作",
          type: "error",
        });
        return;
      }
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeOrganization({ id: this.deleteParams }).then((res) => {
            if (res.code === 10000) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getOrganizationList();
              this.$emit("getOrganizationBox");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 表格 查看、编辑
    handleClick(val, mode) {
      organizationDetail({ id: val.id }).then((res) => {
        if (res.code === 10000) {
          this.formData = res.data;
          this.formData.area = [
            this.formData.province_id,
            this.formData.city_id,
            this.formData.district_id,
          ];
          // console.log(this.formData.area);
          this.formData.property = this.formData.property + "";
          this.formData.status = this.formData.status + "";
          this.formData.branch_type = this.formData.branch_type + "";
          this.formData.region = this.formData.region;
          this.mode = mode;
          this.showOrgDialog = true;
          this.handleChangebranchType(this.formData.branch_type + "");
          this.PageBranchRegionlist(this.areaData2, val, this.formData.region);
        }
      });
    },
    // 选择地址
    handleAddrChange(val) {
      // console.log(val, "val");
      if (val) {
        this.formData.province_id = Number(val[0]);
        this.formData.city_id = Number(val[1]);
        this.formData.district_id = Number(val[2]);
      }
    },
    handleCloseDialog() {
      this.showOrgDialog = false;
    },

    handleOrgCurrentChange(val) {
      this.oPaginations.pageIndex = val;
      this.getOrganizationList();
    },
    handleOrgSizeChange(val) {
      this.oPaginations.pageSize = val;
      this.getOrganizationList();
    },
    handleSelectionChange(val) {
      this.deleteParams = val.map((item) => item.id);
    },
    clcikShowFn(val) {
      // console.log(val.paneName, 11111111);
    },
    handleOpen(key, keyPath) {
      // console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      // console.log(key, keyPath);
    },
    handleSelect(key, keyPath) {
      const id = keyPath.pop();
      this.getQueryorganization({ id });
    },
    // 组织列表
    getOrganizationBox() {
      organizationBox().then((res) => {
        this.organizations = res;
      });
    },
    // 组织列表
    getOrganizationList() {
      organizationList({
        pid: String(this.currentOrgInfo.id),
        page: this.oPaginations.pageIndex,
        page_size: this.oPaginations.pageSize,
      }).then((res) => {
        this.orgList = res.data.list;
        this.oPaginations.total = res.data.pagination.total;
      });
    },
    // 新增组织
    handleClickOk() {
      // console.log(this.formData.region, 33333);
      this.$refs["orgform"].validate((valid) => {
        if (!valid) return;
        this.formData.province_id = Number(this.formData.province_id);
        this.formData.city_id = Number(this.formData.city_id);
        this.formData.district_id = Number(this.formData.district_id);
        this.formData.property = this.formData.property + "";
        this.formData.status = this.formData.status + "";
        this.formData.branch_type = this.formData.branch_type + "";
        this.formData.region = this.formData.region;
        //查看
        if (this.mode === "detail") {
          this.showOrgDialog = false;
          // 编辑
        } else if (this.mode === "edit") {
          this.formData.pid = String(this.formData.pid);
          amendNewlyorgan(this.formData).then((res) => {
            if (res.code === 10000) {
              this.$message({
                type: "success",
                message: "修改成功!",
              });
              this.getOrganizationList();
              this.$emit("getOrganizationBox");
              this.showOrgDialog = false;
            }
          });
          // 新增
        } else {
          this.formData.pid = this.currentOrgInfo.id + "";
          newlyorganization(this.formData).then((res) => {
            if (res.code === 10000) {
              this.$message({
                type: "success",
                message: "新建成功!",
              });
              this.getOrganizationList();
              this.$emit("getOrganizationBox");
              this.showOrgDialog = false;
            }
          });
        }
      });
    },
    // 修改组织
    PageamendNewlyorgan() {
      amendNewlyorgan().then((res) => {
        // console.log("删除预警内容");
      });
    },
    // 查询组织
    getQueryorganization(params) {
      queryorganization(params).then((res) => {
        // console.log("查询组织", res);
        this.currentOrgInfo = res;
        this.getOrganizationList();
      });
    },
    // 停用组织
    Pagebolckorganization() {
      bolckorganization().then((res) => {
        // console.log("停用组织");
      });
    },
    PageBranchRegionlist(dataList, val, region) {
      let areaDataList = JSON.stringify(dataList);
      this.areaData24 = JSON.parse(areaDataList);
      var params = {};
      if (this.mode == "edit") {
        params.id = val.id;
      } else {
        params = {};
      }
      BranchRegionlist(params).then((res) => {
        if (res.code == "10000") {
          // 取出的是已经存在的数组
          let arryList = res.data.list.reduce(function (a, b) {
            return a.concat(b);
          });
          let timeList = Array.from(new Set(arryList));
          let arryList2 = [];
          if (region != null) {
            arryList2 = region.reduce(function (a, b) {
              return a.concat(b);
            });
          } else {
          }
          let timeList2 = Array.from(new Set(arryList2));
          this.areaData24.forEach((itme) => {
            if (timeList.includes(itme.id)) {
              itme.next_level_data.forEach((value) => {
                if (
                  timeList.includes(value.id) &&
                  !timeList2.includes(value.id)
                ) {
                  value.disabled = true;
                }
              });
            }
          });
          this.$forceUpdate();
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.el-form-item--mini .el-form-item__content {
  width: 260px !important;
}

/deep/.ruleForm .el-select {
  width: 260px !important;
}

/deep/.el-cascader {
  width: 260px !important;
}

/deep/.cityOverflow .el-cascader__tags {
  height: 50px !important;
  overflow: hidden !important;
  overflow-y: auto !important;
}
</style>
